package j2EE.doaction.impl;

import j2EE.bean.MailingBean;
import j2EE.doaction.Action;
import j2EE.factory.MailingBeanFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with Intel IDEA.
 *  该动作也负责在UserBean 不存在的情况下创建初始的UserBean
 * @Auther: gjt
 * @Date: 2024/9/8 9:43
 */
public class LoginAction implements Action {
    public static final String USERNAME_ATTR = "userbean";
    private static final String NAME_PARAM = "username";
    private static final String PASSWORD_PARAM = "password";

    @Override
    public boolean performAction(HttpServletRequest request, ServletContext context) {
        // 获取请求参数
        String userName = request.getParameter(NAME_PARAM);
        String password = request.getParameter(PASSWORD_PARAM);

        // 查找UserBean, 如果有必要则进行创建
        HttpSession session = request.getSession();
        MailingBean userBean= (MailingBean)session.getAttribute(USERNAME_ATTR);

        if(userBean == null){
            MailingBean mailingBean = MailingBeanFactory.newInstance();
            session.setAttribute(USERNAME_ATTR, mailingBean);
        }

        // 尝试登录，返回结果
        userBean.setUserName(userName);
        userBean.setPassword(password);
        return userBean.doLogin();
    }
}
